package com.lx.util;//说明:


import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Map;

import static com.lx.util.LX.RequestMethod.*;

/**
 * 创建人:游林夕/2019/3/27 1 */
class LXHttp {
    // 默认超时时间
    private final static int DEFAULT_TIMEOUT = 300000;
    static String doPost(String url, String body,Map<String, String> headers){
        return LX.inputStreamToString(httpInputStream(url,POST, new ByteArrayInputStream(LX.str(body).getBytes(StandardCharsets.UTF_8)), headers,DEFAULT_TIMEOUT, false));
    }
    public static String doPost(String url, String body, Map<String, String> headers, int timeout, boolean exMsgByFailure , Charset charset) {
        return LX.inputStreamToString(httpInputStream(url,POST, new ByteArrayInputStream(LX.str(body).getBytes(charset)), headers,timeout, exMsgByFailure),charset);
    }
    static InputStream doPostInputStream(String url, String body, Map<String, String> headers, int timeout , boolean exMsgByFailure){
        return httpInputStream(url,POST, new ByteArrayInputStream(LX.str(body).getBytes(StandardCharsets.UTF_8)), headers,timeout, exMsgByFailure);
    }

    static String doGet(String url,Map<String, String> headers){
        return LX.inputStreamToString(httpInputStream(url,GET, null, headers,DEFAULT_TIMEOUT, false));
    }
    static String doGet(String url,Map<String, String> headers, int timeout, boolean exMsgByFailure,Charset charset){
        return LX.inputStreamToString(httpInputStream(url,GET, null, headers,timeout, exMsgByFailure),charset);
    }
    static InputStream doGetStream(String url,Map<String, String> headers, int timeout, boolean exMsgByFailure,Charset charset){
        return httpInputStream(url,GET, null, headers,timeout, exMsgByFailure);
    }
    public static String doPut(String url, String body, Map<String, String> headers, int timeout, boolean exMsgByFailure) {
        return LX.inputStreamToString(httpInputStream(url,PUT, new ByteArrayInputStream(LX.str(body).getBytes(StandardCharsets.UTF_8)), headers,timeout, exMsgByFailure));
    }
    static String doDelete(String url,Map<String, String> headers, int timeout, boolean exMsgByFailure){
        return LX.inputStreamToString(httpInputStream(url,DELETE, null, headers,timeout, exMsgByFailure));
    }

    static InputStream httpInputStream(String url, LX.RequestMethod method, InputStream body, Map<String,String> headers, int timeout, boolean exMsgByFailure){
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod(method.name());
            //设置默认Content-Type
            connection.setRequestProperty("Content-Type", "application/json");
            if (LX.isNotEmpty(headers)){
                for (Map.Entry<String,String> e : headers.entrySet()){
                    connection.setRequestProperty(e.getKey() ,e.getValue());
                }
            }
            connection.setDoOutput(PUT.equals(method)|| POST.equals(method));
            connection.setConnectTimeout(timeout);
            connection.setReadTimeout(timeout);
            if (LX.isNotEmpty(body)){
                LX.inputStreamToOutputStream(body, connection.getOutputStream());
            }
            try {
                return connection.getInputStream();
            }catch (Exception e){
                if (exMsgByFailure){
                    throw new RuntimeException(e +"\n"+ LX.inputStreamToString(connection.getErrorStream()));
                }else{
                    return connection.getErrorStream();
                }
            }
        }catch (Exception e){
            return LX.exMsg(e);
        }
    }
    
    
    





    static {
        try {
            //https 默认信任证书
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier((urlHostName, session) -> true);
        } catch (Exception e) {
        }
    }

    private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[1];
        trustAllCerts[0] = new TrustAllManager();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }



    private static class TrustAllManager implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType) { }
        public void checkClientTrusted(X509Certificate[] certs, String authType) { }
    }

}
